$(function() {
	var startDateDefault = moment().subtract('days', 6);// 7 days ago
	var endDateDefaul = moment();
	var startPicker = moment().subtract('days', 6).format('YYYY/MM/DD');
	var endPicker = moment().format('YYYY/MM/DD');
	var provinceSelect = "";
	var citySelect = "";
	var today = moment();
	var yestoday = moment().subtract('days', 1);
	var sevenDay = moment().subtract('days', 6);
	var Day29 = moment().subtract('days', 29);
	var thisMonthBegin = moment().startOf('month');
	var thisMonthEnd = moment().endOf('month');
	var lastMonthBegin = moment().subtract('month', 1).startOf('month');
	var lastMonthEnd = moment().subtract('month', 1).endOf('month');

	var cb = function(start, end, label) {
		$('#timeRange span').html(
				start.format('YYYY/MM/DD') + ' - ' + end.format('YYYY/MM/DD'));
	};

	var optionSet1 = {
		startDate : startDateDefault,
		endDate : endDateDefaul,
		dateLimit : {
			days : 31
		},
		showDropdowns : true,
		showWeekNumbers : true,
		timePicker : false,
		timePickerIncrement : 1,
		timePicker12Hour : true,
		ranges : {
			'Today' : [ today, today ],
			'Yestoday' : [ yestoday, yestoday ],
			'Last 7 days' : [ sevenDay, today ],
			'Last 30 days' : [ Day29, today ],
			'This Month' : [ thisMonthBegin, thisMonthEnd ],
			'Last Month' : [ lastMonthBegin, lastMonthEnd ]
		},
		opens : 'right',
		buttonClasses : [ 'btn btn-default' ],
		applyClass : 'btn-small btn-primary',
		cancelClass : 'btn-small',
		format : 'YYYY-MM-DD',
		separator : ' to ',
		locale : {
			applyLabel : 'Apply',
			cancelLabel : 'Cancel',
			fromLabel : 'From',
			toLabel : 'To',
			customRangeLabel : 'Custom',
			daysOfWeek : [ 'Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa' ],
			monthNames : [ 'January', 'February', 'March', 'April', 'May',
					'June', 'July', 'August', 'September', 'October',
					'November', 'December' ],
			firstDay : 1
		}
	};

	$('#timeRange span').html(
			startDateDefault.format('YYYY/MM/DD') + ' - '
					+ endDateDefaul.format('YYYY/MM/DD'));
	drawTable(startDateDefault.format('YYYY/MM/DD'), endDateDefaul
			.format('YYYY/MM/DD'));
	provinceTable(startDateDefault.format('YYYY/MM/DD'), endDateDefaul
			.format('YYYY/MM/DD'));
	$.ajax({
		url : window.basePath + "configuration/suggest/province",
		type : 'POST',
		success : function(data) {
			for ( var i = 0; i < data.length; i++) {
				var text = "<option>" + data[i] + "</option>";
				$("#province").append(text);
			}
			$("#province").selectpicker('refresh');

		}
	});

	$('#timeRange').daterangepicker(optionSet1, cb);
	$('#timeRange').on('apply.daterangepicker', function(ev, picker) {
		startPicker = picker.startDate.format('YYYY/MM/DD');
		endPicker = picker.endDate.format('YYYY/MM/DD');
		drawTable(startPicker,endPicker);
		if(provinceSelect!="ALL" && provinceSelect!=""){
				if(citySelect!="ALL" && citySelect!=""){
					districtTable(startPicker,endPicker,provinceSelect,citySelect);
				}else{
					cityTable(startPicker,endPicker,provinceSelect);
				}
		}else{
			provinceTable(startPicker,endPicker);
		}
	});
	$('#timeRange').on('cancel.daterangepicker', function(ev, picker) {
		console.log("cancel event fired");
	});

	$("#province").selectpicker({
		style : 'btn',
		size : 8,
		showContent : false
	});
	$("#city").selectpicker({
		style : 'btn',
		size : 8,
		showContent : false
	});

	function loadCity(province) {
		$("#city").html("<option>ALL</option>");
		$.ajax({
			url : window.basePath + "configuration/loadCity",
			type : 'POST',
			data : {
				province : province
			},
			success : function(data) {
				for ( var i = 0; i < data.length; i++) {
					var text = "<option>" + data[i] + "</option>";
					$("#city").append(text);
				}
				$("#city").selectpicker('refresh');

			}
		});
	}

	$("#province").on('change', function() {
		provinceSelect = $(this).val();
		if ($(this).get(0).selectedIndex != 0) {
			loadCity($(this).val());
			$('#city').prop('disabled', false);
			$('#city').selectpicker('refresh');
			cityTable(startPicker, endPicker, $(this).val());
		} else {
			$("#city").html("<option>ALL</option>");
			$('#city').prop('disabled', true);
			$('#city').selectpicker('refresh');
			provinceTable(startPicker, endPicker);
		}
	});

	$("#city").on(
			'change',
			function() {
				citySelect = $(this).val();
				if ($(this).get(0).selectedIndex != 0) {
					districtTable(startPicker, endPicker, provinceSelect, $(
							this).val());
				} else {
					cityTable(startPicker, endPicker, provinceSelect);
				}
			});

	function drawTable(startDate, endDate) {
		$(".table thead tr").html("<th>Location&nbsp;&nbsp;&nbsp;&nbsp;</th>");
		$(".table tbody").html("");
		var date = moment(startDate, 'YYYY-MM-DD');
		var eDate = moment(endDate, 'YYYY-MM-DD');
		eDate.add('days', 1);
		var theadContent;
		while (date.diff(eDate, 'days') < 0) {
			theadContent = date.format('YYYY-MM-DD');
			$(".table thead tr").append(
					"<th>" + theadContent + "&nbsp;&nbsp;&nbsp;&nbsp;</th>");
			date.add('days', 1);
		}
	}

	function writetable(tableId, data) {
		$(tableId + " tbody").html("");
		for ( var i = 0; i < data.length; i++) {
			var td = "";
			var k = 0;
			$(tableId + " thead tr th")
					.each(
							function() {
								if (k > 0) {
									var flag = 0;
									for ( var j = 0; j < data[i].info.length; j++) {
										var thHtml = $(this).html().split(
												"&nbsp;");
										if (thHtml[0] == data[i].info[j].date) {
											var valueF = parseFloat(data[i].info[j].value);
											if (valueF > 0) {
												td += "<td class='warning'>"
														+ data[i].info[j].value
														+ "%";
											} else {
												td += "<td>0";
											}

											td += "</td>";
											flag = 1;
										}
									}
									if (flag == 0) {
										td += "<td>0</td>";
									}
								}

								k = k + 1;
							});

			$(tableId + " tbody").append(
					"<tr><td>" + data[i].location + "</td>" + td + "<tr/>");
		}
		$(tableId).tablesorter({
			widgets : [ 'zebra' ],
		// widthFixed: true
		});
	}
	function provinceTable(start, end) {
		$.ajax({
			url : window.basePath + "log/provinceList",
			type : 'POST',
			data : {
				start : start,
				end : end
			},
			success : function(data) {
				writetable("#locationAnalysis", data);
			}
		});

		$.ajax({
			url : window.basePath + "log/provinceDfa",
			type : 'POST',
			data : {
				start : start,
				end : end
			},
			success : function(data) {
				writetable("#locationDfaAnalysis", data);
			}
		});

		$.ajax({
			url : window.basePath + "log/provinceFt",
			type : 'POST',
			data : {
				start : start,
				end : end
			},
			success : function(data) {
				writetable("#locationFtAnalysis", data);
			}
		});
	}

	function cityTable(start, end, province) {
		$.ajax({
			url : window.basePath + "log/cityList",
			type : 'POST',
			data : {
				start : start,
				end : end,
				province : province
			},
			success : function(data) {
				writetable("#locationAnalysis", data);
			}
		});

		$.ajax({
			url : window.basePath + "log/cityDfa",
			type : 'POST',
			data : {
				start : start,
				end : end,
				province : province
			},
			success : function(data) {
				writetable("#locationDfaAnalysis", data);
			}
		});

		$.ajax({
			url : window.basePath + "log/cityFt",
			type : 'POST',
			data : {
				start : start,
				end : end,
				province : province
			},
			success : function(data) {
				writetable("#locationFtAnalysis", data);
			}
		});
	}

	function districtTable(start, end, province, city) {
		$.ajax({
			url : window.basePath + "log/districtList",
			type : 'POST',
			data : {
				start : start,
				end : end,
				province : province,
				city : city
			},
			success : function(data) {
				writetable("#locationAnalysis", data);
			}
		});

		$.ajax({
			url : window.basePath + "log/districtDfa",
			type : 'POST',
			data : {
				start : start,
				end : end,
				province : province,
				city : city
			},
			success : function(data) {
				writetable("#locationDfaAnalysis", data);
			}
		});

		$.ajax({
			url : window.basePath + "log/districtFt",
			type : 'POST',
			data : {
				start : start,
				end : end,
				province : province,
				city : city
			},
			success : function(data) {
				writetable("#locationFtAnalysis", data);
			}
		});
	}

});
